#include "../include/head.h"
void login_user(u_list *user_list)
{
    if (user_list == NULL)
    {
        ERRLOG("链表为空\n");
        return;
    }
    u_node *ptr = user_list->next;
    char name[20];
    char passwd[20];
    int num = 0;
    while (1)
    {
        if (num == 3)
        {
            printf("超过三次登录失败，请稍后再试\n");
            return;
        }
        printf("请输入用户名或id:");
        scanf("%s", name);
        printf("请输入密码：");
        scanf("%s", passwd);
        while (ptr != NULL)
        {
            if (strcmp(ptr->userm->name, name) == 0 && strcmp(ptr->userm->passwd, passwd) == 0)
            {
                printf("登录成功\n");
                return;
            }
            ptr = ptr->next;
        }
        printf("用户名或密码错误\n");
        num++;
    }
}
//注册用户
void register_user(u_list *user_list)
{

    if (user_list == NULL)
    {
        ERRLOG("链表为空\n");
        return;
    }
    u_node *ptr = user_list->next;
    user_t user = {0};
    printf("请输入用户名:"); //输入用户名
    scanf("%s", user.name);
    printf("请输入密码:"); //输入密码
    scanf("%s", user.passwd);
    while (ptr != NULL)
    {
        if (strcmp(ptr->userm->name, user.name) == 0)
        {
            printf("用户名已存在\n");
            return;
        }
        ptr = ptr->next;
    }
    insert_node(user_list,user,1);
    save_user_list(user_list);
    printf("注册成功\n");
    return;
}
// 将用户表写入文件
void save_user_list(u_list *user_list)
{
    if (user_list == NULL)
    {
        ERRLOG("链表为空\n");
        return;
    }
    u_node *ptr = user_list->next;
    FILE *fp = fopen("/home/student/code/project/data/regular_users.txt", "w");
    if (fp == NULL)
    {
        ERRLOG("文件打开失败\n");
        return;
    }
    fprintf(fp, "用户身份证信息 用户名  密码  票价 \n");
    while (ptr != NULL)
    {
        fprintf(fp, "\t%d\t\t  %s\t  %s\t%d\n", ptr->userm->IDcard, ptr->userm->name, ptr->userm->passwd, ptr->userm->value);
        ptr = ptr->next;
    }
    fclose(fp);
}
// 将文件中的用户表读入
u_list *load_user_list()
{
    u_list *list = (u_list *)malloc(sizeof(u_list));
    if (list == NULL)
    {
        ERRLOG("头节点创建失败\n");
        return NULL;
    }
    list->next = NULL;
    FILE *fp = fopen("/home/student/code/project/data/regular_users.txt", "r");
    if (fp == NULL)
    {
        ERRLOG("文件打开失败\n");
        return list;
    }
    fclose(fp);
    return list;
}